// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Xsl;
using System.IO;
using System.Data.SqlClient;
using InterpriseSuiteEcommerceCommon.Tool;

namespace InterpriseSuiteEcommerceCommon.DTO
{
    [Serializable, XmlRoot(ElementName = "SalesOrderHistory")]
    public class SalesOrderHistoryCollection
    {
        #region Variable Declaration

        private Customer _thisCustomer = null;
        private int _rows = 0;
        private int _current = 0;
        private int _pages = 0;
        private int _allPages = 0;
        private int _start = 0;
        private int _end = 0;
        private List<SalesOrderHistory> _allOrders = new List<SalesOrderHistory>();

        #endregion

        [XmlIgnore()]
        public Customer ThisCustomer
        {
            get { return _thisCustomer; }
        }

        [XmlElement(ElementName = "Rows")]
        public int Rows
        {
            get { return _rows; }
            set { throw new NotSupportedException(); }
        }

        [XmlElement(ElementName = "Current")]
        public int Current
        {
            get { return _current; }
            set { throw new NotSupportedException(); }
        }

        [XmlElement(ElementName = "Pages")]
        public int Pages
        {
            get { return _pages; }
            set { throw new NotSupportedException(); }
        }

        [XmlElement(ElementName = "AllPages")]
        public int AllPages
        {
            get { return _allPages; }
            set { throw new NotSupportedException(); }
        }

        [XmlElement(ElementName = "Start")]
        public int Start
        {
            get { return _start; }
            set { throw new NotSupportedException(); }
        }

        [XmlElement(ElementName = "End")]
        public int End
        {
            get { return _end; }
            set { throw new NotSupportedException(); }
        }

        [XmlArray(ElementName = "SalesOrders"),
        XmlArrayItem(ElementName = "SalesOrder", Type = typeof(SalesOrderHistory))]
        public List<SalesOrderHistory> Items
        {
            get { return _allOrders; }
            set { throw new NotSupportedException(); }
        }    

        public void Add(SalesOrderHistory order)
        {
            _allOrders.Add(order);
        }

        public static SalesOrderHistoryCollection ForCustomer(Customer thisCustomer, int pages, int current)
        {
            SalesOrderHistoryCollection allOrders = new SalesOrderHistoryCollection();
            allOrders._thisCustomer = thisCustomer;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, "exec dbo.eCommerceGetWebOrder @CustomerCode = {0}, @WebSiteCode = {1}, @Pages = {2}, @Current = {3}, @ContactCode = {4}", DB.SQuote(thisCustomer.CustomerCode), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode), pages, current,  DB.SQuote(thisCustomer.ContactCode)))
                {// first try to read the headers part
                    // should just be one row
                    if (reader.Read())
                    {
                        allOrders._rows = DB.RSFieldInt(reader, "Rows");
                        allOrders._current = DB.RSFieldInt(reader, "Current");
                        allOrders._pages = DB.RSFieldInt(reader, "Pages");
                        allOrders._allPages = DB.RSFieldInt(reader, "AllPages");
                        allOrders._start = DB.RSFieldInt(reader, "Start");
                        allOrders._end = DB.RSFieldInt(reader, "End");
                    }

                    // now let's read the details if any
                    if (allOrders.Rows > 0 && reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            SalesOrderHistory order = SalesOrderHistory.New(thisCustomer,
                                                        DB.RSFieldInt(reader, "Row"),
                                                        DB.RSField(reader, "SalesOrderCode"),
                                                        DB.RSFieldDateTime(reader, "SalesOrderDate"),
                                                        DB.RSFieldDateTime(reader, "ShippingDate"),
                                                        DB.RSFieldDecimal(reader, "TotalRate"),
                                                        DB.RSField(reader, "Notes"),
                                                        DB.RSField(reader, "TransactionState"),
                                                        DB.RSField(reader, "PaymentMethod"),
                                                        DB.RSFieldDateTime(reader, "DownloadEmailSentDate"),
                                                        DB.RSFieldInt(reader, "ElectronicDownloadItemCount"));
                            allOrders.Add(order);
                        }
                    }
                }
            }

            return allOrders;
        }

        public string Serialize()
        {
            StringBuilder logSerialization = new StringBuilder();

            using (StringWriter sw = new StringWriter(logSerialization))
            {
                using (XmlWriter writer = new XmlTextWriter(sw))
                {
                    XmlSerializer serializer = new XmlSerializer(this.GetType());
                    serializer.Serialize(writer, this);
                }
            }

            return logSerialization.ToString();
        }

        public string Display()
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(this.Serialize());

            XslCompiledTransform transform = new XslCompiledTransform(false);

            XsltArgumentList args = new XsltArgumentList();
            args.AddExtensionObject("urn:ise", this);

            XmlUrlResolver resolver = new XmlUrlResolver();
            resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;            

            string result = string.Empty;
            string package = string.Empty;

            if (CurrentContext.IsRequestingFromMobileMode(Customer.Current))
            {
                package = CommonLogic.SafeMapPath("mobile/XmlPackages/page.orderhistory.xml.config");
            }
            else
            {
                package = CommonLogic.SafeMapPath("XmlPackages/page.orderhistory.xml.config");
            }

            transform.Load(package);

            using (MemoryStream strm = new MemoryStream())
            {
                transform.Transform(doc, args, strm);

                strm.Position = 0;
                using (StreamReader reader = new StreamReader(strm))
                {
                    result = reader.ReadToEnd();
                }
            }

            return result;
        }

        public string FormatDate(DateTime date, string format)
        {
            return date.ToString(format, ThisCustomer.Culture);
        }

        public string FormatCurrency(Decimal value)
        {
            return ThisCustomer.FormatBasedOnMyCurrency(value);
        }

        public string StringResource(String StringResourceName)
        {
            if (AppLogic.AppConfigBool("ShowStringResourceKeys"))
            {
                return StringResourceName;
            }
            string result = String.Empty;
            if (StringResourceName.Length != 0)
            {
                result = AppLogic.GetString(StringResourceName, ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }
            return result;
        }

    }
}




